package common

import (
	"blog_go/global"
	"blog_go/models"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

// 批量删除的封装
func ComDelete[T any](model T, req models.DeleteRequest) (count int) {
	// 按照id查询
	var list []T
	affected := global.DB.Find(&list, req.IdList).RowsAffected
	if affected == 0 {
		panic("数据都不存在")
	}
	// 把查询出来的全部删除 需要开启事物
	err := global.DB.Transaction(func(tx *gorm.DB) error {
		db := tx.Delete(&list)
		if db.Error != nil {
			logrus.Error(db.Error)
			return db.Error
		}
		return nil
	})
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	return len(list)
}
